/**
 * build_project
 * <p>
 * Copyright 2014 cayden.cn, Inc. All rights reserved.
 *
 * @author Administrator
 * @date 2021-07-08 17:45
 */
package com.cayden.config.boot.component;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.support.SpringFactoriesLoader;

import java.util.List;

/**
 *
 * @author cayden
 * @date 2021-07-08 17:45
 */
@Order(value = Ordered.LOWEST_PRECEDENCE)
@Slf4j
public class ComponentExtensionContextInitializer implements ApplicationContextInitializer {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        if (applicationContext.getEnvironment().getPropertySources().get("bootstrap") == null) {
            //new DevModeDetector().apply(applicationContext.getEnvironment());
            String[] exclude = applicationContext.getEnvironment()
                    .getProperty("spring.autoconfigure.exclude", String[].class);
            if (exclude == null) {
                exclude = new String[0];
            }
            List<String> excludes = Lists.newArrayList(exclude);
            List<ComponentInitializer> componentInitializers = SpringFactoriesLoader.loadFactories(
                    ComponentInitializer.class, applicationContext.getClassLoader());

            componentInitializers.forEach(
                    componentInitializer -> {
                        componentInitializer.initialize(applicationContext);
                        excludes.addAll(componentInitializer.excludeAutoconfigClassNames());
                    });

            // 添加禁用spring-security的AutoConfiguration
            excludes.add(
                    "org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration");
            if (!excludes.isEmpty()) {
                System.setProperty("spring.autoconfigure.exclude", Joiner.on(',').join(excludes));
            }
        }
    }
}
